package com.caigou.modules.vote.ui.unlike

import android.graphics.Color
import android.os.Bundle
import android.text.Html
import android.text.TextUtils
import android.view.View
import androidx.activity.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.adapter.CommentItemAdapter
import com.caigou.comm.base.adapter.PrizeBallItemAdapter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.bean.CommentBean
import com.caigou.comm.base.bean.OpenPrizeVoBean
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseActivity
import com.caigou.comm.base.ext.*
import com.caigou.comm.base.utils.ImageLoader
import com.caigou.comm.base.utils.MediaUtils
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.comm.base.widget.YearPickDialog
import com.caigou.modules.vote.R
import com.caigou.modules.vote.adpter.VoteItemAdapter
import com.caigou.modules.vote.bean.UnlikeBean
import com.caigou.modules.vote.bean.VoteItemBean
import com.caigou.modules.vote.databinding.ActivityUnlikeBinding
import com.caigou.modules.vote.viewmodel.LikeViewModel
import com.caigou.modules.vote.viewmodel.UnlikeViewModel
import com.google.android.material.tabs.TabLayout
import dagger.hilt.android.AndroidEntryPoint
import java.util.*

/**
 * @author #Suyghur.
 * Created on 2021/12/30
 */
@Route(path = RouterPath.Vote.PAGE_UNLIKE)
@AndroidEntryPoint
class UnlikeActivity : BaseActivity() {

    private lateinit var binding: ActivityUnlikeBinding
    private val unlikeViewModel: UnlikeViewModel by viewModels()
    private val likeViewModel: LikeViewModel by viewModels()

    @JvmField
    @Autowired(name = AppConstants.YEAR)
    var year = ""

    private val periods = mutableListOf<String>()

    @JvmField
    @Autowired(name = AppConstants.PERIOD)
    var tranPeriod: Int = 0

    private var period: Int = 0

    private var page = 1
    private val limit = 10
    private var totalPage = 0
    private var sort = 0

    private var dataId = 0

    private val commentItemAdapter: CommentItemAdapter by lazy {
        CommentItemAdapter(mutableListOf())
    }

    private val prizeAdapter: PrizeBallItemAdapter by lazy {
        PrizeBallItemAdapter(mutableListOf())
    }

    private val voteAdapter: VoteItemAdapter by lazy {
        VoteItemAdapter(mutableListOf())
    }

    private val yearDialog by lazy {
        YearPickDialog(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityUnlikeBinding.inflate(layoutInflater)
        setContentView(binding.root)
        containerId = binding.unlikeLlContainer.id
        initView()
    }

    private fun initView() {
        ARouter.getInstance().inject(this)

        if (TextUtils.isEmpty(year)) {
            year = Calendar.getInstance().get(Calendar.YEAR).toString()
        }

        binding.unlikeSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                fetchUnlikeDetail()
            }
        }

        binding.unlikeTabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                tab?.apply {
                    period = periods[position].toInt()
                    fetchUnlikeDetail()
                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
            }

        })

        binding.unlikeBtnYear.text = year
        binding.unlikeBtnYear.setOnClickListener {
            yearDialog.show()
        }
        yearDialog.tvConfirm.setOnClickListener {
            year = yearDialog.getYear().toString()
            binding.unlikeBtnYear.text = year
            fetchPeriodList()
            yearDialog.dismiss()
        }

        binding.unlikeTvBack.setOnClickListener {
            finish()
        }

        binding.unlikeLlShare.setOnClickListener {
            val bitmap = binding.unlikeLlContainer.screenCapture()
            MediaUtils.saveBitmap(this, bitmap)
            showToast("截图已保存到系统相册")
        }

        commentItemAdapter.loadMoreModule.run {
            setOnLoadMoreListener {
                commentItemAdapter.loadMoreModule.isEnableLoadMore = true
                fetchCommentList()
            }
            isAutoLoadMore = true
            isEnableLoadMoreIfNotFullPage = false
        }
        binding.unlikeRecyclerViewComment.run {
            layoutManager = LinearLayoutManager(this@UnlikeActivity)
            adapter = commentItemAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(this@UnlikeActivity))
        }
        commentItemAdapter.setOnItemChildClickListener { _, view, position ->
//            clickPos = position
            val item = commentItemAdapter.data[position]
            when (view.id) {
                R.id.item_comment_iv_avatar -> {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, item.replyUserInfoVo.userId)
                        .navigation()
                }
                R.id.item_comment_ll_content -> {
                    ARouter.getInstance().build(RouterPath.Vote.PAGE_COMMENT_DETAIL)
                        .withObject(AppConstants.COMMENT_ITEM_BEAN, item)
                        .withInt(AppConstants.DATA_TYPE, 3)
                        .navigation()
                }
                R.id.item_comment_iv_like -> {
                    if (AppBackgroundInfo.instance.hasLogin) {
                        if (item.like) {
                            showToast("您已经点过赞了")
                        } else {
                            likeViewModel.setCommentLike(item.replyId, AppBackgroundInfo.instance.userBean!!.userId, item.replyUserInfoVo.userId, 3)
                        }
                    } else {
                        ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                    }
                }
                R.id.item_comment_btn_reply -> {
                    if (AppBackgroundInfo.instance.hasLogin) {
                        ARouter.getInstance()
                            .build(RouterPath.Vote.PAGE_COMMENT_REPLY)
                            .withObject(AppConstants.COMMENT_ITEM_BEAN, item)
                            .withObject(AppConstants.COMMENT_ROOT_ITEM_BEAN, item)
                            .withInt(AppConstants.DATA_TYPE, 3)
                            .navigation()
                    } else {
                        ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                    }
                }
            }
        }

        binding.unlikeRgSelector.setOnCheckedChangeListener { group, _ ->
            sort = when (group.checkedRadioButtonId) {
                binding.unlikeBtnSequential.id -> 1
                binding.unlikeBtnReverse.id -> 0
                else -> 0
            }
            page = 1
            fetchCommentList()
        }

        LiveDataBus.get().with(BusKey.REPLY_SUCCESS, Any::class.java).observe(this) {
            fetchCommentList()
        }
        fetchPeriodList()
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(unlikeViewModel.periodListLiveData, ::handleGetPeriodList)
        observe(unlikeViewModel.unlikeDetailLiveData, ::handleGetUnlikeDetail)
        observe(unlikeViewModel.commentListLiveData, ::handleGetCommentList)
        observe(likeViewModel.voteLikeLiveData, ::handleSetVoteLike)
        observe(likeViewModel.commentLikeLiveData, ::handleSetCommentLike)
    }

    private fun handleGetPeriodList(result: Resource<MutableList<String>>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.unlikeSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.unlikeSwipeRefreshLayout.isRefreshing = false
                result.data?.apply {
                    binding.unlikeTabLayout.removeAllTabs()
                    periods.clear()
                    if (isNotEmpty()) {
                        binding.unlikeLlEmpty.visibility = View.GONE
                        binding.unlikeLlContent.visibility = View.VISIBLE
                        periods.addAll(this)
                        period = this[0].toInt()
                        forEachIndexed { idx, value ->
                            val tab = binding.unlikeTabLayout.newTab()
                            tab.text = value
                            binding.unlikeTabLayout.addTab(tab, idx)
                        }
                        if (tranPeriod != 0 && periods.isNotEmpty()) {
                            val index = periods.indexOf(tranPeriod.toString())
                            binding.unlikeTabLayout.selectTab(binding.unlikeTabLayout.getTabAt(index))
                        }
                        fetchUnlikeDetail()
                    } else {
                        binding.unlikeLlEmpty.visibility = View.VISIBLE
                        binding.unlikeLlContent.visibility = View.GONE
                    }
                }
            }
        }
    }

    private fun handleGetUnlikeDetail(result: Resource<UnlikeBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.unlikeSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.unlikeSwipeRefreshLayout.isRefreshing = false
                if (result.data == null) {
                    binding.unlikeLlEmpty.visibility = View.VISIBLE
                    binding.unlikeLlContent.visibility = View.GONE
                } else {
                    binding.unlikeLlEmpty.visibility = View.GONE
                    binding.unlikeLlContent.visibility = View.VISIBLE
                    dataId = result.data!!.unlikeId
                    fetchCommentList()
                    handleDetailUI(result.data!!)
                }
            }
        }
    }

    private fun handleGetCommentList(result: Resource<CommentBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.unlikeSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取评论列表异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.unlikeSwipeRefreshLayout.isRefreshing = false
                if (result.data == null) {
                    binding.unlikeLlEmptyComment.visibility = View.VISIBLE
                    binding.unlikeRecyclerViewComment.visibility = View.GONE
                    return
                }
                if (result.data!!.list.isNullOrEmpty()) {
                    binding.unlikeLlEmptyComment.visibility = View.VISIBLE
                    binding.unlikeRecyclerViewComment.visibility = View.GONE
                } else {
                    binding.unlikeLlEmptyComment.visibility = View.GONE
                    binding.unlikeRecyclerViewComment.visibility = View.VISIBLE
                }

                totalPage = result.data!!.totalPage

                if (page == 1) {
                    commentItemAdapter.setList(result.data!!.list)
                } else {
                    commentItemAdapter.addData(result.data!!.list)
                }

                if (result.data!!.pageSize < limit) {
                    commentItemAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    commentItemAdapter.loadMoreModule.loadMoreComplete()
                }

                if (page >= totalPage) {
                    commentItemAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    page++
                }
            }
        }
    }

    private fun handleSetVoteLike(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.unlikeSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("点赞异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.unlikeSwipeRefreshLayout.isRefreshing = false
                result.data?.apply {
                    showToast(this)
                    fetchUnlikeDetail()
                }
            }
        }
    }


    private fun handleSetCommentLike(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.unlikeSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("点赞异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.unlikeSwipeRefreshLayout.isRefreshing = false
                result.data?.apply {
                    showToast(this)
                    fetchCommentList()
                }
            }
        }
    }


    private fun handleDetailUI(bean: UnlikeBean) {
        handlePrize(bean.openPrizeVo)
        handleVote(bean.voteList)
        binding.unlikeTvTime.text = bean.createTime
        binding.unlikeTvBrowseNum.text = "阅读：${bean.browseCount}"
        binding.unlikeTvTitle.text = bean.title
        binding.unlikeTvContent.text = Html.fromHtml(bean.content)
        if (TextUtils.isEmpty(bean.cover)) {
            binding.unlikeIvCover.visibility = View.GONE
        } else {
            binding.unlikeIvCover.visibility = View.VISIBLE
            ImageLoader.load(this@UnlikeActivity, bean.cover, binding.unlikeIvCover)
            binding.unlikeIvCover.setOnClickListener {
                showImgPreview(this, bean.cover)
            }
        }

        if (AppBackgroundInfo.instance.hasLogin) {
            if (TextUtils.isEmpty(AppBackgroundInfo.instance.userBean!!.headImg)) {
                binding.unlikeIvMyAvatar.setImageResource(R.drawable.img_comm_avatar)
            } else {
                ImageLoader.loadCircle(this, AppBackgroundInfo.instance.userBean!!.headImg, binding.unlikeIvMyAvatar)
            }
        } else {
            binding.unlikeIvMyAvatar.setImageResource(R.drawable.img_comm_avatar)
        }

        binding.unlikeTvLikeNum.text = bean.likeCount.toString()
        if (bean.like) {
            binding.unlikeIvLike.setImageResource(R.drawable.img_vote_like)
            binding.unlikeTvLikeNum.setTextColor(Color.parseColor("#FE6880"))
        } else {
            binding.unlikeIvLike.setImageResource(R.drawable.img_vote_unlike)
            binding.unlikeTvLikeNum.setTextColor(Color.parseColor("#505050"))
        }
        binding.unlikeLlLike.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                if (bean.like) {
                    showToast("您已经点过赞了")
                } else {
                    likeViewModel.setVoteLike(bean.unlikeId, AppBackgroundInfo.instance.userBean!!.userId, 3)
                }
            } else {
                showToast("请您先登录")
            }
        }

        binding.unlikeTvCommentNum.text = bean.replyCount.toString()

        binding.unlikeBtnReply.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                ARouter.getInstance().build(RouterPath.Vote.PAGE_REPLY)
                    .withInt(AppConstants.DATA_ID, bean.unlikeId)
                    .withInt(AppConstants.DATA_TYPE, 3)
                    .withString(AppConstants.RECEIVER_ID, "")
                    .navigation()
            } else {
                showToast("请您先登录")
            }
        }

        binding.unlikeLlComment.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                ARouter.getInstance().build(RouterPath.Vote.PAGE_REPLY)
                    .withInt(AppConstants.DATA_ID, bean.unlikeId)
                    .withInt(AppConstants.DATA_TYPE, 3)
                    .withString(AppConstants.RECEIVER_ID, "")
                    .navigation()
            } else {
                showToast("请您先登录")
            }
        }
    }

    private fun handlePrize(bean: OpenPrizeVoBean) {
        if (bean.prizeList.isNullOrEmpty()) {
            binding.unlikeTvPrizeTitle.visibility = View.GONE
            binding.unlikeLlPrize.visibility = View.GONE
        } else {
            binding.unlikeTvPrizeTitle.visibility = View.VISIBLE
            binding.unlikeLlPrize.visibility = View.VISIBLE

            binding.unlikeTvPrizeTitle.text = "第${bean.period}期开奖结果"
            binding.unlikeRecyclerViewPrize.run {
                layoutManager = GridLayoutManager(this@UnlikeActivity, 6)
                adapter = prizeAdapter
                itemAnimator = DefaultItemAnimator()
                addItemDecoration(SpaceItemDecoration(this@UnlikeActivity))
            }

            val size = bean.prizeList.size
            val balls = bean.prizeList.slice(0..size - 2)
            prizeAdapter.setList(balls)
            val lastBall = bean.prizeList[size - 1]
            binding.unlikePrizeTvNum.text = lastBall.number.toString()
            binding.unlikePrizeTvNum.setBackgroundResource(prizeBallColor(lastBall.numberColor))
            binding.unlikePrizeTvDesc.text = lastBall.animalName
        }
    }

    private fun handleVote(voteList: MutableList<VoteItemBean>) {
        if (voteList.isNullOrEmpty()) {
            binding.unlikeRecyclerViewVote.visibility = View.GONE
        } else {
            binding.unlikeRecyclerViewVote.visibility = View.VISIBLE

            binding.unlikeRecyclerViewVote.run {
                layoutManager = GridLayoutManager(this@UnlikeActivity, 2)
                adapter = voteAdapter
                itemAnimator = DefaultItemAnimator()
                addItemDecoration(SpaceItemDecoration(this@UnlikeActivity))
            }

            voteAdapter.setList(voteList)
        }
    }

    private fun fetchPeriodList() {
        unlikeViewModel.getPeriodList(year.toInt())
    }

    private fun fetchUnlikeDetail() {
        val userId = if (AppBackgroundInfo.instance.hasLogin) {
            AppBackgroundInfo.instance.userBean!!.userId
        } else {
            ""
        }
        unlikeViewModel.getUnlikeDetail(year.toInt(), period, userId)
    }

    private fun fetchCommentList() {
        val userId = if (AppBackgroundInfo.instance.hasLogin) {
            AppBackgroundInfo.instance.userBean!!.userId
        } else {
            ""
        }
        unlikeViewModel.getCommentList(page, limit, dataId, sort, userId)
    }
}